﻿using AutoMapper;
using MediatR;
using MyMES.Domain.yjb;
using MyMES.Error;
using MyMES.Infrastructure.Interface;
using MyMES.Read.API.Application.Commends.settingCommand;
using MyMES.Read.API.FileNlog;

namespace MyMES.Read.API.Application.CommendHandlers.settingCommand
{
    public class ProcessInfoCommandHandlers : IRequestHandler<ProcessInfoCommand, APIPaging<List<ProcessInfo>>>
    {
        private readonly IBaseRepository<ProcessInfo> accreop;
        private readonly IMapper mapper;
        private readonly Nolgs nolgs;

        public ProcessInfoCommandHandlers(IBaseRepository<ProcessInfo> accreop, IMapper mapper, Nolgs nolgs)
        {
            this.accreop = accreop;
            this.mapper = mapper;
            this.nolgs = nolgs;
        }

        /// <summary>
        /// 工序显示
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<APIPaging<List<ProcessInfo>>> Handle(ProcessInfoCommand request, CancellationToken cancellationToken)
        {
            var startTime = DateTime.Now;
            try
            {
              
                APIPaging<List<ProcessInfo>> result = new APIPaging<List<ProcessInfo>>();
                result.Code = APIEnum.查询失败;
                result.Msg = "查询成功";
                string sql = "select * from ProcessInfo where IsDelete=true ORDER BY ProcessInfoId DESC";

                var list = await accreop.SelectAsync(sql);
                if (!string.IsNullOrEmpty(request.ProcessCode))
                {
                    list = list.Where(x => x.ProcessCode.Contains(request.ProcessCode)).ToList();
                }
                if (!string.IsNullOrEmpty(request.ProcessName))
                {
                    list = list.Where(x => x.ProcessName.Contains(request.ProcessName)).ToList();
                }
                if (request.IsEnabled.HasValue)
                {
                    list = list.Where(x => x.IsEnabled == request.IsEnabled.Value).ToList();
                }

                result.TotalCount = list.Count;
                result.TotalPage = (int)Math.Ceiling(result.TotalCount * 1.0 / request.Size);
                list = list.Skip((request.Index - 1) * request.Size).Take(request.Size).ToList();

                result.data = list;
                return result;
            }
            catch (Exception)
            {

                throw;
            }
            finally
            {
                var endTime = System.DateTime.Now;

                var durationInDays = (endTime - startTime).Days;
                nolgs.GetNlogs(
                    request.ProcessName ?? "Unknow", "工序显示列表", "False", durationInDays, "异常信息"
                    );
            }
        }
    }
}
